package han.message;

import com.han.http.client.method.HttpPost;
import com.han.http.client.paramter.FormDataPair;
import com.han.http.client.paramter.RequestHeader;
import com.han.http.fetch.Fetcher;
import han.entity.MessageEntity;
import han.proof.SmartqqProof;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: Han
 * @date: 2018/7/11 13:31
 * @dscription: 接受信息线程
 */
public class MessageListener implements Runnable {

    private static Logger logger = LoggerFactory.getLogger(MessageListener.class);

    private LinkedBlockingQueue<MessageEntity> messageQueue;
    private boolean isRunning;
    private ThreadPoolExecutor poolExecutor;

    public MessageListener(LinkedBlockingQueue<MessageEntity> messageQueue) {
        this.messageQueue = messageQueue;
        isRunning = true;

        int corePoolSize = 10;
        int maximumPoolSize = 128;
        long keepAliveTime = 30;
        TimeUnit timeUnit = TimeUnit.SECONDS;
        ArrayBlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(1024);
        poolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, blockingQueue);
    }

    @Override
    public void run() {
        logger.info("消息轮询线程启动");
        SmartqqProof smartqqProof = SmartqqProof.getInstance();
        String psessionid = smartqqProof.getPsessionid();
        String cookie = smartqqProof.getCookie().replaceAll("; uin=[o]?", "; uin=o");
        Fetcher fetcher = new Fetcher();
        String urlStr = "https://d1.web2.qq.com/channel/poll2";
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "d1.web2.qq.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Content-Length", "331"),
                new RequestHeader("Origin", "https://d1.web2.qq.com"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"),
                new RequestHeader("Content-Type", "application/x-www-form-urlencoded"),
                new RequestHeader("Accept", "*/*"),
                new RequestHeader("Referer", "https://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2"),
                new RequestHeader("Accept-Encoding", "gzip, deflate"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", cookie)
        };
        FormDataPair[] formDataPairs = {
                new FormDataPair("r", "{\"ptwebqq\":\"\",\"clientid\":53999199,\"psessionid\":\""
                        + psessionid + "\"," + "\"key\":\"\"}")
        };
        int connectTimeout = 1000 * 10;
        int readTimeout = 1000 * 60;
        while (isRunning) {
            try {
                String msg = fetcher.getPageInfoByPost(urlStr, requestHeaders, formDataPairs, connectTimeout,
                        readTimeout, false, HttpPost.UTF_8, null);
                poolExecutor.submit(new MessageReceiver(msg, messageQueue));
            } catch (NullPointerException ignore) {
            } catch (Exception e) {
                logger.info(e.toString());
                StackTraceElement[] stackTraceElements = e.getStackTrace();
                for (StackTraceElement stackTraceElement : stackTraceElements) {
                    logger.error(stackTraceElement.toString());
                }
            }
        }
        //结束之后,等待所有消息线程停止
        poolExecutor.shutdown();
        logger.info("消息轮询线程结束");
    }

    /**
     * 停止接收
     */
    public void close() {
        isRunning = false;
    }
}
